package handler

import (
	"context"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"github.com/smartwalle/xid"
	"net/http"
	"strconv"
	"week1/client/global"
	"week1/ordersrv/ordersrv"

	"github.com/zeromicro/go-zero/rest/httpx"
	"week1/client/internal/logic"
	"week1/client/internal/svc"
	"week1/client/internal/types"
)

func AliPayHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var (
			orderSn = r.FormValue("orderSn")
		)

		//查询订单信息
		res, err := svcCtx.OrderRpc.GetOrderDetail(context.Background(), &ordersrv.GetOrderDetailReq{OrderSn: orderSn})
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		//查询订单信息
		var tradeNo = fmt.Sprintf("%d", xid.Next())
		var p = alipay.TradePagePay{}
		//通知
		p.NotifyURL = global.KServerDomain + "/v1/ali/notify"
		//回调
		p.ReturnURL = global.KServerDomain + "/v1/ali/callback"
		p.Subject = "尚鑫平的订单:" + tradeNo
		p.OutTradeNo = tradeNo
		p.TotalAmount = strconv.Itoa(int(res.OrderTotal))
		p.ProductCode = "FAST_INSTANT_TRADE_PAY"

		// 支付宝支付
		url, _ := global.AliClient.TradePagePay(p)
		r.Form.Set("orderSn", url.String())

		var req types.AliPayReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewAliPayLogic(r.Context(), svcCtx)
		resp, err := l.AliPay(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
